package MsgSystem;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TransferRequest {

    private static final Log LOGGER = LogFactory.getLog("common");
    boolean finalFile = false;

    public boolean Receive(ImpInstantMessage itm, FileTransferRequest request) {
        LOGGER.info("The File Listener has listenned an attemp and it will prepare to receive the file");
        File file = new File("outcoming");
        IncomingFileTransfer transfer = request.accept();

        try {
            LOGGER.info("The received file it will save in: " + file.getAbsolutePath() + "\\" + request.getFileName() + " path");
            transfer.recieveFile(new File(file.getAbsoluteFile() + "/" + request.getDescription() + ".jpg"));
            LOGGER.info("The file has been saved in your disk");

        } catch (XMPPException ex) {
            LOGGER.info("An error has been ocurred receiving the file");
            Logger.getLogger(ReceiveMessages.class.getName()).log(Level.SEVERE, null, ex);
        }
        while (transfer.isDone() != true) {
            if (transfer.getStatus().equals(FileTransfer.Status.error)) {
                LOGGER.info("ERROR!!! " + transfer.getError());
            } else {
                if (transfer.getProgress() == 1.0) {
                    finalFile = true;
                    break;
                }
                finalFile = this.getBoolean();
                if (transfer.getProgress() == 0.5) {
                    LOGGER.info(transfer.getProgress() * 100);

                }
                if (transfer.getProgress() == 0.75) {
                    LOGGER.info(transfer.getProgress() * 100);

                }
                if (finalFile == true) {
                    break;
                }
            }

        }
        finalFile = true;
        return finalFile;
    }

    public void setBoolean(boolean cancel) {
        finalFile = cancel;
    }

    public boolean getBoolean() {
        return finalFile;
    }
}
